package swa.telco.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import swa.telco.impl.ImplClientProvider;
import swa.telco.impl.SWAProvider;
import swa.telco.interfaces.ClientProviderInt;
import swa2012.telco.broker.BrokerCallback;

/**
 * Servlet implementation class ProviderManagerServlet
 */
@WebServlet("/ProviderManagerServlet")
public class ProviderManagerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	SWAProvider swaprovider;
	
	JaxWsServerFactoryBean clientFactoryBean;
	JaxWsServerFactoryBean cbFactoryBean;
	
	StringBuffer logString;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ProviderManagerServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// START PROVIDER //
		if(request.getParameter("action").contentEquals("StartProvider")){
			
			
			logString = new StringBuffer();
						
			swaprovider = new SWAProvider(logString);
			
			clientFactoryBean = new JaxWsServerFactoryBean();
			clientFactoryBean.setServiceClass(ClientProviderInt.class);
			clientFactoryBean.setAddress("http://morpheusx.at:8101/Provider/ProviderService");
			clientFactoryBean.setServiceBean(swaprovider.getClientProvider());
			clientFactoryBean.create();
			
			cbFactoryBean = new JaxWsServerFactoryBean();
			cbFactoryBean.setServiceClass(BrokerCallback.class);
			cbFactoryBean.setAddress("http://morpheusx.at:8101/Provider/BrokerCallbackService");
			cbFactoryBean.setServiceBean(swaprovider.getBrokerCb());
			cbFactoryBean.create();
			
			try {
				
				swaprovider.startCallBack(new URI("http://morpheusx.at:8101/Provider/BrokerCallbackService"));
			} catch (URISyntaxException e) {
				e.printStackTrace();
			}
			
			PrintWriter out = response.getWriter();
			out.write(logString.toString());
			out.close();
		}
		
		// STOP PROVIDER //
		if(request.getParameter("action").contentEquals("StopProvider")){
			
			swaprovider.stop();
			
			clientFactoryBean.destroy();
			cbFactoryBean.destroy();
			
			PrintWriter out = response.getWriter();
			out.write(logString.toString());
			out.close();
		}
		
		// SHOW LOGS //
		if(request.getParameter("action").contentEquals("ShowLogs")){
			PrintWriter out = response.getWriter();
			out.write("showing Logs ...");
			out.close();
		}
	}

}
